<?php
if( !defined( 'HIGHLIGHT_LINK' ) ) {
	define( 'HIGHLIGHT_LINK', 'pages' );
}

if( KF_EDITOR_MODE == 'Markdown' ) {
	include_once( Foundry::config('libPath').'/markdown.php' );
} else {
	include_once( Foundry::config('libPath').'/Textile.php' );
}


class hdms_pageAdminController extends FoundryControllerInterface
{


	/**
	 * init()
	 *
	 * init() is called in place of the __construct() method used by the
	 * FoundryControllerInterface super class
	 * This function will be called immediately after the __construct method
	 *
	 */ 
	public function init()
	{
	
	
	}
	
	public function main()
	{
	
		return true;
	}

	public function edit()
	{
		$user = FoundryRegistry::get( 'USER_session');
		
		$id = FoundryRequest::get( 'id', 'num' );
		
		$pageTags = array();
		
		if( !$id || !is_numeric( $id ) ) {
			$id = false;
		} else {
			$page = $this->page( $id );
			$tags = $page->tags;
			
			if( !empty( $tags ) ) {
				foreach( $tags as $tag ) {
					$pageTags[] = $tag->uid;
				}
			}
		}
		
		if( $user->checkKey() ) {
			$title = cleanString( FoundryRequest::post( 'pageTitle', 'alnum' ) );
			$content = cleanString( FoundryRequest::post( 'pageContent', 'alnum' ) );
			$tags = FoundryRequest::post( 'pageTagID', 'valid_array' );
			$published = FoundryRequest::post( 'pagePublished', 'num' );
									
			if( $title && $content ) {
				
				if( $id === false ) {
					$page = $this->page();
				}
				
				$page->title = $title;
				$page->content = $content;
				
				if( KF_EDITOR_MODE == 'Markdown' ) {
					$page->content_markdown = Markdown( $page->content );
				} else {
					$content = preg_replace(
						"/&quot;([a-zA-Z0-9\-_ ]*)&quot;\:/",
						'"$1":',
						$page->content );
				
					$textile = new Textile;
					$page->content_markdown = $textile->process(
						$content );
				}
				
				$page->modified = strtotime( 'today' );
				
				if( $published == 1 ) {
					$page->published = 1;
				} else {
					$page->published = -1;
				}
				
				$page->save();
			
				if( is_array( $tags ) && !empty( $tags ) ) {
					$page->setManyReference( 'tags', $tags );
				}
		
				header( "Location: ".
					FoundryView::helperLinkTo( 'pageAdmin/edit/'.$page->uid.'/sv' ) );
				exit;
					
				
			}
		}
		
		$key = $user->generateKey();
	
		return array( 'key' => $key, 'page'	=> $page, 'pageTags' => $pageTags );	
	}
	
	public function publish()
	{
		$id = FoundryRequest::post( 'id', 'num' );
		
		if( $id ) {
			$page = $this->page( $id );
			
			if( $page->uid ) {
				$page->published = 1;
				$page->save();
				
				return array( 'saved' => 1 );
			}
		}
		
		return array( 'saved' => 0 );
	}
	
	public function deletePage()
	{
		$id = FoundryRequest::post( 'id', 'num' );
		
		if( $id ) {
			$page = $this->page( $id );
			
			if( $page->uid ) {
				$page->delete();
				
				return array( 'saved' => 1 );
			}
		}
		
		return array( 'saved' => 0 );
		
	}

}

?>